/**=========================================================
 * Controller: SystemRoleController
  =========================================================*/
App.controller('SystemRoleController', ['$scope', 'toaster', 'ngDialog', 'Utils', 'HttpUtils', 'DialogUtils', 'SimpleUiGrid',
    function($scope, toaster, ngDialog, utils, httpUtils, dialogUtils, simpleUiGridService) {
        $scope.currentRole = {};  
//===========================tree=================================
        httpUtils.get('/sysMenu/getAllMenus',{},function(result){
             $scope.menuTreeOption = {
                name: "menuTree",
                setting: {
                    check: {
                        enable: true
                    },
                    view: {
                        showLine: true,
                        selectedMulti: false
                    },
                    data: {
                        key: {
                            name: 'label'
                        }
                    }
                },
                data: result.datas
             }
        })
        
        $scope.expandAll = function(){
            $scope.menuTree.expandAll(true);
        }
        
        $scope.collapseAll = function(){
            $scope.menuTree.expandAll(false);
        } 
        
        var checkTree = function(){
            $scope.menuTree.checkAllNodes(false);
            $scope.menuTree.expandAll(false);
            if (!utils.isEmpty($scope.currentRole.id)){
                var params = {
                    namespace: 'SystemMapper.getRoleMenu',
                    roleID: $scope.currentRole.id
                }
                
                httpUtils.get(utils.getQueryListUrl(),params,
                    function(result){
                        var datas = result.datas.gridDatas;
                        for (var i = 0; i < datas.length; i++){
                            var menuNode = $scope.menuTree.getNodeByParam('tid',datas[i].menu_id);
                            if (!utils.isEmpty(menuNode)){
                                $scope.menuTree.checkNode(menuNode,true);
                                if (menuNode.level == 0){
                                    $scope.menuTree.expandNode(menuNode,true,true,false);
                                }
                            }
                        }
                    }
                );
            }
        }
        
        $scope.saveRoleMenu = function(){
            if (!utils.isEmpty($scope.currentRole.id)){
                $scope.saveButton = 0.1;
                var checkedNodes = $scope.menuTree.getCheckedNodes(),
                    checkedMenus = '';
                for (var i = 0; i < checkedNodes.length; i++){
                    checkedMenus += checkedNodes[i].tid + ','
                }

                $scope.saveButton = 0.8;
                httpUtils.post('/sysRole/saveRoleMenu',
                    {
                        roleID: $scope.currentRole.id,
                        menuIDs: checkedMenus
                    },
                    function(result){
                        if (result.success){
                            toaster.pop('success', '', '保存成功');
                        }else{
                            toaster.pop('error', '', result.msg);
                        }
                        $scope.saveButton = false;
                    },
                    function(){
                        toaster.pop('error', '', '保存失败');
                    }
                );
            }
        }

//===========================roleGrid=================================            
        var roleGridColumns = [
            {
                displayName: '角色编号',
                field: 'code'
            },
            {
                displayName: '角色名称',
                field: 'name'
            },
            {
                displayName: '备注',
                field: 'remark'
            },
            {
                displayName: '状态',
                field: 'status',
                width: '80'
            },
            { 
                name: '', 
                field: 'widgets', 
                width: '100',
                enableCellEdit: false,
                cellTemplate: '\
                    <div class="ui-grid-cell-contents" style="text-align:center;">\
                        <button ng-click="grid.appScope.selectUser(row.entity)" title="维护用户" class="btn btn-xs btn-success">\
                            <em class="fa fa-users"></em>\
                        </button>\
                        <button ng-click="grid.appScope.saveRole(row.entity)" title="保存" class="btn btn-xs btn-info">\
                            <em class="fa fa-save"></em>\
                        </button>\
                        <button ng-click="grid.appScope.deleteRole(row.entity)" title="删除" class="btn btn-xs btn-danger">\
                            <em class="fa fa-trash"></em>\
                        </button>\
                    </div>\
                '
            }
        ];

        $scope.queryParams = {namespace: 'SystemMapper.getAllRoles'};
        $scope.searchRoleGrid = function() {
            $scope.currentRole = {};
            roleUserGrid.clear();
            roleGrid.draw($scope.queryParams);
            if (!utils.isEmpty($scope.menuTree)){
                checkTree();
            }
        }; 

        var roleGrid = simpleUiGridService.init($scope, 
            {
                optionModel: 'roleGridOptions',
                pageOptionModel: 'roleGridPageOptions',
                gridApi: 'roleGridApi',
                pageType: 'common',
                needExport: false,
                columns: roleGridColumns,
                controllerSearchFn: $scope.searchRoleGrid,
                menus: [
                    {
                        title: '新增',
                        action: function ($event) {
                            roleGrid.addRow({status: '1'},0);
                        }
                    }
                ],
                registerApiFn: function(gridApi){
                    gridApi.selection.on.rowSelectionChanged($scope, function (row, event) {
                        $scope.currentRole.id = row.entity.tid;
                        searchRoleUserGrid();
                        checkTree();
                    });
                }
            }
        );   
       
        $scope.saveRole = function(data){
            httpUtils.post('/sysRole/save',data,
                function(result){
                    if (result.success){
                        if (utils.isEmpty(data.tid)){
                            data.tid = result.msg;
                        }
                        $scope.currentRole.id = result.msg;
                        toaster.pop('success', '', '保存成功');
                    }else{
                        toaster.pop('error', '', result.msg);
                    }
                },
                function(){
                    toaster.pop('error', '', '保存失败');
                }
            );
        };
        
        $scope.deleteRole = function(data){
            dialogUtils.confirm('确定要删除吗?',
                function (value) {
                    httpUtils.post('/sysRole/delete',data,
                        function(result){
                            if (result.success){
                                roleGrid.deleteRow(data);
                                toaster.pop('success', '', '删除成功');
                            }else{
                                toaster.pop('error', '', result.msg);
                            }
                        },
                        function(result){
                            toaster.pop('error', '', '删除失败');
                        }
                    );
                }
            );
        };
        
        $scope.refreshCache = function(){
             httpUtils.get('/sysRole/refreshRoleMenuCache?refreshMenuUrlCache=true',{},
                function(result){
                    if (result.success){
                        toaster.pop('success', '', '刷新成功');
                    }else{
                        toaster.pop('error', '', result.msg);
                    }
                },
                function(){
                    toaster.pop('error', '', '刷新失败');
                }
            );
        }
        
        $scope.selectUser = function(data){
            ngDialog.openConfirm({
                template: 'selectUserDialog',
                className: 'ngdialog-theme-default',
                appendClassName: 'ngdialog-lg',
                scope:$scope,
                controller: ['$scope', function($scope) {
                    $scope.searchOtherUserSelectGrid(data.tid);
                    $scope.searchRoleUserSelectGrid(data.tid);
                }]
            }).then(function (value) {
                var userIDs = '',
                    selectedUsers = roleUserSelectGrid.getAll();
                
                for (var i = 0; i < selectedUsers.length; i++){
                    userIDs += selectedUsers[i].tid + ",";
                }
                
                httpUtils.post('/sysRole/saveRoleUser',
                    {
                        roleID: $scope.currentRole.id,
                        userIDs: userIDs
                    },
                    function(result){
                        if (result.success){
                            toaster.pop('success', '', '配置成功');
                            searchRoleUserGrid();
                        }else{
                            toaster.pop('error', '', result.msg);
                        }
                    },
                    function(result){
                        toaster.pop('error', '', '配置失败');
                    }
                );
            });
        }
        
        $scope.goLeft = function(){
            if (otherUserSelectGrid.getSelection().length > 0){
                for (var i = 0; i < otherUserSelectGrid.getSelection().length; i++){
                    roleUserSelectGrid.addRow(otherUserSelectGrid.getSelection()[i]);
                    otherUserSelectGrid.deleteRow(otherUserSelectGrid.getSelection()[i]);
                } 
            }   
        }
        
        $scope.goRight = function(){
            if (roleUserSelectGrid.getSelection().length > 0){
                for (var i = 0; i < roleUserSelectGrid.getSelection().length; i++){
                    otherUserSelectGrid.addRow(roleUserSelectGrid.getSelection()[i]);
                    roleUserSelectGrid.deleteRow(roleUserSelectGrid.getSelection()[i]);
                } 
            }
        }

//===========================roleUserSelectGrid=================================
        var roleUserSelectGridColumns = [
            {
                displayName: '用户编号',
                field: 'code'
            },
            {
                displayName: '用户名称',
                field: 'cnname'
            },
            {
                displayName: '状态',
                field: 'status',
                width: '80'
            }
        ];     
               
        $scope.searchRoleUserSelectGrid = function(id) {
            if (utils.isEmpty(id)){
                roleUserSelectGrid.clear();
            }else {
                var params = {
                    namespace: 'SystemMapper.getRoleUser',
                    roleID: id
                }

                roleUserSelectGrid.draw(params);
            }
        }; 

        var roleUserSelectGrid = simpleUiGridService.init($scope, 
            {
                optionModel: 'roleUserSelectGridOptions',
                gridApi: 'roleUserSelectGridApi',
                columns: roleUserSelectGridColumns,
                needPage: false,
                needExport: false,
                multiSelect: true
            }
        );       
 //===========================otherUserSelectGrid================================= 
        $scope.selectFilterParams = {namespace: 'SystemMapper.getOtherUser'};
        var otherUserSelectGridColumns = [
            {
                displayName: '用户编号',
                field: 'code'
            },
            {
                displayName: '用户名称',
                field: 'cnname'
            }
        ];                 
        $scope.searchOtherUserSelectGrid = function(id) {
            if (utils.isEmpty(id)){
                otherUserSelectGrid.clear();
            }else {
                $scope.selectFilterParams.roleID = id;

                otherUserSelectGrid.draw($scope.selectFilterParams);
            }
        }; 

        var otherUserSelectGrid = simpleUiGridService.init($scope, 
            {
                optionModel: 'otherUserSelectGridOptions',
                gridApi: 'otherUserSelectGridApi',
                columns: otherUserSelectGridColumns,
                needPage: false,
                needExport: false,
                multiSelect: true
            }
        );      
//===========================roleUserGrid=================================        
        var roleUserGridColumns = [
            {
                displayName: '用户编号',
                field: 'code'
            },
            {
                displayName: '用户名称',
                field: 'cnname'
            },
            {
                displayName: '状态',
                field: 'status',
                width: '80'
            }
        ];
            
        var searchRoleUserGrid = function() {
            if (utils.isEmpty($scope.currentRole.id)){
                roleUserGrid.clear();
            }else {
                var params = {
                    namespace: 'SystemMapper.getRoleUser',
                    roleID: $scope.currentRole.id
                }

                roleUserGrid.draw(params);
            }
        }; 

        var roleUserGrid = simpleUiGridService.init($scope, 
            {
                optionModel: 'roleUserGridOptions',
                pageOptionModel: 'roleUserGridPageOptions',
                gridApi: 'roleUserGridApi',
                pageType: 'common',
                needExport: false,
                columns: roleUserGridColumns,
                controllerSearchFn: searchRoleUserGrid
            }
        );   
//===========================init================================= 
        $scope.searchRoleGrid();
    }
]);
